package org.rency.common.utils.converts;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.rency.common.utils.domain.SYSDICT;

public class CommonConvert {
	
	/**
	 * 将Map对象转换为Java Bean
	 * </br>Created on 2015年12月21日
	 * @param map
	 * @param obj
	 * @return 转换后Java Bean对象
	 * @throws Exception
	 */
	public static Object map2Bean(Map<String, Object> map,Object obj) throws Exception{
		try{
			if(map == null || map.isEmpty()){
				return obj;
			}
			BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
			PropertyDescriptor[] descriptor = beanInfo.getPropertyDescriptors();
			for(PropertyDescriptor property : descriptor){
				String propName = property.getName();
				if(map.containsKey(propName)){
					Object value = map.get(propName);
					Method setter = property.getWriteMethod();
					setter.invoke(obj, value);
				}
			}
		}catch(Exception e){
			throw new Exception(e);
		}
		return obj;
	}
	
	/**
	 * 将Java Bean对象转换为Map
	 * </br>Created on 2015年12月21日
	 * @param obj
	 * @return 转换后Map
	 * @throws Exception
	 */
	public static Map<String, Object> bean2Map(Object obj) throws Exception {  
        if(obj == null){  
            return null;  
        }
        Map<String, Object> map = new HashMap<String, Object>();  
        try{
        	BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());  
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();  
            for (PropertyDescriptor property : propertyDescriptors) {  
                String key = property.getName();  
                if (!key.equals("class")) {  
                    Method getter = property.getReadMethod();  
                    Object value = getter.invoke(obj);  
                    map.put(key, value);  
                }  
            }  
        }catch(Exception e){
        	throw e;
        }
        return map;  
  
    } 

	/**
	 * 将URL中的参数转换为Map对象
	 * </br>Created on 2015年12月21日
	 * @param urlParam
	 * @param charset 解码字符集,如果为空则不解码
	 * @return 转换后Map对象
	 * @throws Exception
	 */
	public static Map<String, String> urlParam2Map(String urlParam,String charset) throws Exception{
		Map<String, String> map = new HashMap<String, String>();
		try{
			if(StringUtils.isBlank(urlParam)){
				return map;
			}
			List<String> sections = Arrays.asList(urlParam.split(SYSDICT.SPLIT_CHAR_URL));
			for(String section : sections){
				if(section.indexOf("=") != -1){
					String[] keyValue = section.split("=");
					String key = "";
					String value = "";
					if(keyValue.length == 1){
						key = keyValue[0].trim();
					}
					if(keyValue.length == 2){
						key = keyValue[0].trim();
						value = keyValue[1].trim();
					}
					if(StringUtils.isNotBlank(charset)){
						map.put(URLDecoder.decode(key, charset), URLDecoder.decode(value, charset));
					}else{
						map.put(key, value);
					}
				}
			}
		}catch(Exception e){
			throw new Exception(e);
		}
		return map;
	}
	
	/**
	 * 将Map对象转换为URL参数形式
	 * </br>Created on 2015年12月21日
	 * @param params
	 * @param charset 转码字符集,如果为空则不转码
	 * @return
	 * @throws IOException
	 */
	public static String map2UrlParam(Map<String, String> params, String charset) throws IOException {
		if (params == null || params.isEmpty()) {
			return "";
		}

		StringBuilder query = new StringBuilder();
		Set<Entry<String, String>> entries = params.entrySet();
		boolean hasParam = false;

		for (Entry<String, String> entry : entries) {
			String name = entry.getKey();
			String value = entry.getValue();
			// 忽略参数名或参数值为空的参数
			if (StringUtils.isNotBlank(name) && StringUtils.isNotBlank(value)) {
				if (hasParam) {
					query.append("&");
				} else {
					hasParam = true;
				}
				query.append(name).append("=");
				if(StringUtils.isNotBlank(charset)){
					query.append(URLEncoder.encode(value, charset));
				}else{
					query.append(value);
				}
			}
		}

		return query.toString();
	}
	
	/**
	 * 将字符串转换为ASCII并拼接成一个字符串
	 * </br>Created on 2016年1月13日
	 * @param data
	 * @return
	 */
	public static String convertToASCII(String data){
		if(StringUtils.isBlank(data)){
			return data;
		}
		StringBuilder builder = new StringBuilder();
		for(char c : data.toCharArray()){
			int ascii = (int) c;
			builder.append(ascii);
		}
		return builder.toString();
	}
}